package com.lsy.weizhi2.customview;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.lsy.weizhi2.JsonObject.ActivityListObject;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.activity.ActivityList;
import com.lsy.weizhi2.adapter.HeadImageAdapter;
import com.lsy.weizhi2.adapter.ImageAdapterBig;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.mybase.BaseApp;
import com.lsy.weizhi2.myutils.NoteDetailUPCall;
import com.lsy.weizhi2.myutils.UserInfoCall;
import com.lsy.weizhi2.utils.MyMethod;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.autolayout.utils.AutoLayoutHelper;

/**
 * Created by 嗨哟 on 2017/3/18.
 */
public class ActivityDetailUp extends AutoRelativeLayout implements View.OnClickListener{
    private Context context;
    private RelativeLayout activity_detail_gallery;
    private ViewPager activity_detail_vp;
    private RecyclerView activity_detail_up_rv;
    private UserInfo activity_detail_user_info;
    private TextView activity_detail_title, activity_detail_image_num,activity_detail_content,
            activity_detail_baoming_num, activity_detail_reply_num, activity_detail_look_num;
    private HeadImageAdapter headImageAdapter;
    private NoteDetailUPCall noteDetailUPCall;
    private ViewPager activity_detail_vp_2;
    private ImageAdapterBig imageAdapterBig;
    private int size;
    public ActivityDetailUp(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        LayoutInflater.from(context).inflate(R.layout.activity_detail_up,this,true);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        activity_detail_vp_2= (ViewPager) findViewById(R.id.activity_detail_vp_2);
        activity_detail_gallery= (RelativeLayout) findViewById(R.id.activity_detail_gallery);
        activity_detail_vp= (ViewPager) findViewById(R.id.activity_detail_vp);
        activity_detail_up_rv= (RecyclerView) findViewById(R.id.activity_detail_up_rv);
        activity_detail_user_info= (UserInfo) findViewById(R.id.activity_detail_user_info);
        activity_detail_title= (TextView) findViewById(R.id.activity_detail_title);
        activity_detail_image_num= (TextView) findViewById(R.id.activity_detail_image_num);
        activity_detail_content= (TextView) findViewById(R.id.activity_detail_content);
        activity_detail_baoming_num= (TextView) findViewById(R.id.activity_detail_baoming_num);
        activity_detail_reply_num= (TextView) findViewById(R.id.activity_detail_reply_num);
        activity_detail_look_num= (TextView) findViewById(R.id.activity_detail_look_num);
        LinearLayoutManager manager = new LinearLayoutManager(context);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        activity_detail_up_rv.setLayoutManager(manager);
        activity_detail_baoming_num.setOnClickListener(this);
        activity_detail_reply_num.setOnClickListener(this);
        activity_detail_user_info.setUserInfoCall(new UserInfoCall() {
            @Override
            public void onClick(View view, int flag) {
                switch (flag){
                    case UserInfoCall.FOLLOW:
                        //调用收藏活动接口
                        noteDetailUPCall.onClickFollow(view,UserInfoCall.FOLLOW);
                        break;
                    case UserInfoCall.IMAGE:
                        //跳转用户信息界面
                        break;
                }
            }
        });
    }

    /**
     * 设定活动发布人信息
     */
    public void setUserInfo(String name,int avatar,String guanzhu){
        activity_detail_user_info.setContent(name,avatar,guanzhu);
    }

    /**
     * 设定活动信息
     */
    public void setActivityInfo(ActivityListObject.ListBean bean){
        if(bean!=null){
            activity_detail_title.setText(bean.getTitle());
            String str=bean.getContent();
            Spanned content= Html.fromHtml(str);
            activity_detail_content.setText(content);
            activity_detail_baoming_num.setText(bean.getEnrollment()+"");//报名人数
            activity_detail_reply_num.setText("");//回复人数
            activity_detail_look_num.setText("");//浏览人数
        }else{
            activity_detail_title.setText("活动标题");
            //activity_detail_content.setText("活动内容");
            activity_detail_baoming_num.setText("200");//报名人数
            activity_detail_reply_num.setText("500");//回复人数
            activity_detail_look_num.setText("2000");//浏览人数
        }

    }
    /**
     * 报名人员头像
     */
    public void setHeadImages() {
        headImageAdapter = new HeadImageAdapter(context, null);
        activity_detail_up_rv.setAdapter(headImageAdapter);
    }
    /**
     * 活动图片加载
     */
    public void setActivityImages(int[]str) {
            //设置ViewPager的布局
            Log.i("NoteDetailUp", "SCREEN_HEIGHT==" + BaseApp.REAL_HEIGHT);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    BaseApp.SCREEN_WIDTH * 5 / 10, BaseApp.REAL_HEIGHT * 380 / 1334);
            Log.i("NoteDetailUp", "height==" + params.height);
            /**** 重要部分  ******/
            //clipChild用来定义他的子控件是否要在他应有的边界内进行绘制。 默认情况下，clipChild被设置为true。 也就是不允许进行扩展绘制。
            activity_detail_vp.setClipChildren(false);
            //父容器一定要设置这个，否则看不出效果
            activity_detail_gallery.setClipChildren(false);
            Log.i("NoteDetailUp","str==="+str[0]);
            if(str!=null){
                size=str.length;
                activity_detail_image_num.setText("1/"+size);
            }
            activity_detail_vp.setLayoutParams(params);
            //为ViewPager设置PagerAdapter

            activity_detail_vp.setAdapter(new MyPagerAdapter(str));
            //设置ViewPager切换效果，即实现画廊效果
            activity_detail_vp.setPageTransformer(true, new ZoomOutPageTransformer());
            //设置预加载数量
            activity_detail_vp.setOffscreenPageLimit(2);
            //设置每页之间的左右间隔
            Log.i("NoteDetailUp", "SCREEN_WIDTH==" + BaseApp.SCREEN_WIDTH);
            activity_detail_vp.setPageMargin(BaseApp.SCREEN_WIDTH * 10 / 750);
            activity_detail_vp.addOnPageChangeListener(new MyOnPageChangeListener());
            //将容器的触摸事件反馈给ViewPager
            activity_detail_gallery.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    // dispatch the events to the ViewPager, to solve the problem that we can swipe only the middle view.
                    return activity_detail_vp.dispatchTouchEvent(event);
                }

            });
    }

    public void setActivityImage2(int[]str){
        if(str!=null){
            size=str.length;
            activity_detail_image_num.setText("1/"+size);
        }
        imageAdapterBig = new ImageAdapterBig(context,str);
        activity_detail_vp_2.setAdapter(imageAdapterBig);
        activity_detail_vp_2.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                activity_detail_image_num.setText(i + 1 + "/"+size);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    /**
     * 点击事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.activity_detail_baoming_num:
                noteDetailUPCall.onClickFollow(view,NoteDetailUPCall.BAOMING);
                break;
            case R.id.activity_detail_reply_num:
                noteDetailUPCall.onClickFollow(view,NoteDetailUPCall.ACTIVITY_REPLY);
                break;
        }
    }

    class MyPagerAdapter extends PagerAdapter {
        private int[] str;

        public MyPagerAdapter(int[] str) {
            this.str = str;
        }

        @Override
        public int getCount() {
            //return viewList==null?0:viewList.size();
            return str==null?1:str.length;//ViewPager里的个数
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return (view == object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if(str==null){
                imageView.setImageResource(R.mipmap.nopic);
            }else{
                if(str[0]>1000000){
                    imageView.setImageResource(str[position]);
                }else{
                    Glide.with(context)
                            .load(new GlideUrl(Constants.DOWN_USER_PICTURE+str[position],new LazyHeaders.Builder().addHeader("WZ-AUTH-TOKEN", MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").build()))
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(imageView);
                }
            }
            ((ViewPager) container).addView(imageView);
            return imageView;

        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((ImageView) object);
        }
    }

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int position) {
            //这里做切换ViewPager时，底部RadioButton的操作
            activity_detail_image_num.setText(position + 1 + "/"+size);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if (activity_detail_gallery != null) {
                activity_detail_gallery.invalidate();
            }
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }

    /**
     * 实现的原理是，在当前显示页面放大至原来的MAX_SCALE
     * 其他页面才是正常的的大小MIN_SCALE
     */
    class ZoomOutPageTransformer implements ViewPager.PageTransformer {
        private static final float MAX_SCALE = 1.2f;
        private static final float MIN_SCALE = 0.8f;//0.85f

        @Override
        public void transformPage(View view, float position) {
            //setScaleY只支持api11以上
            if (position < -1) {
                view.setScaleX(MIN_SCALE);
                view.setScaleY(MIN_SCALE);
            } else if (position <= 1) //a页滑动至b页 ； a页从 0.0 -1 ；b页从1 ~ 0.0
            { // [-1,1]
//              Log.e("TAG", view + " , " + position + "");
                float scaleFactor = MIN_SCALE + (1 - Math.abs(position)) * (MAX_SCALE - MIN_SCALE);
                view.setScaleX(scaleFactor);
                //每次滑动后进行微小的移动目的是为了防止在三星的某些手机上出现两边的页面为显示的情况
                if (position > 0) {
                    view.setTranslationX(-scaleFactor * 2);
                } else if (position < 0) {
                    view.setTranslationX(scaleFactor * 2);
                }
                view.setScaleY(scaleFactor);

            } else { // (1,+Infinity]

                view.setScaleX(MIN_SCALE);
                view.setScaleY(MIN_SCALE);

            }
        }

    }

    public void setNoteDetailUPCall(NoteDetailUPCall noteDetailUPCall){
        this.noteDetailUPCall=noteDetailUPCall;
    }

    private final AutoLayoutHelper mHelper = new AutoLayoutHelper(this);
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        if (!isInEditMode())
        {
            mHelper.adjustChildren();
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
